﻿$(window).load(function () {
    $('body').disableSelection();
    $("#accordion").accordion({ heightStyle: "content" });
    $('#themeSelector')
        .change(applyTheme)
        .click(function (event) { this.focus(); event.stopPropagation(); });
    $("#clearLogButton").button().click(function (event) { $('#logTextarea').val(''); });
    $("#buttonApply").button().click(updateOptions);
    $("#buttonDestroy").button().click(toggleDestroy);
    $("#numberOfElements").spinner({ min: 0, max: 1000 });
    $("#numberOfElements").spinner("value", 50);
    
    $('#ScrollableTable').tableScroll({
        numberOfRowsInScrollableArea: 13,
        scrollContainer: $('#scrollContainer'),
        numberOfElementsInDataSource: $("#numberOfElements").spinner("value"),
        scroll: UpdateData
    });

    applyTheme();
});

function applyTheme() {
    SetStyleSheet('themeLink', 'styles/' + $('#themeSelector').val() + '/jquery-ui-1.9.2.css', 'jquery-ui-1.9.2.css');
    SetStyleSheet('scrollStyle', 'styles/' + $('#themeSelector').val() + '/scroll-style.css', 'scroll-style.css');
}

function updateOptions() {
    $('#ScrollableTable').tableScroll({
        numberOfRowsInScrollableArea: 13,
        scrollContainer: $('#scrollContainer'),
        bufferEvents: $("#useEventBuffer").get(0).checked,
        numberOfElementsInDataSource: $("#numberOfElements").spinner("value"),
        scroll: UpdateData
    });
    $('#ScrollableTable').data('tableScroll')._triggerScrollEvent();
}

function UpdateData(event, data) {
    $('.dataCell').html('&nbsp;')
    logEvent(event, data);
    var numberOfElementsInDataSource = $("#numberOfElements").spinner("value");
    for (var i = data.firstElementIndex;
        i < data.firstElementIndex + data.numberOfRowsInScrollableArea 
        && i < numberOfElementsInDataSource; i++) {
        this.rows[i - data.firstElementIndex + data.rowScrollableAreaStartsFrom].cells[0].innerHTML = 'Data row #' + (i + 1);
    }
}

function toggleDestroy(event, data) {
    if ($('#ScrollableTable').data('tableScroll') != null) {
        $('#ScrollableTable').tableScroll('destroy');
        $("#buttonDestroy").button({ label: "Create" });
        $("#buttonApply").button("disable");
    }
    else {
        updateOptions();
        $("#buttonDestroy").button({ label: "Destroy" });
        $("#buttonApply").button("enable");
    }
}

function logEvent(event, data) {
    var description = event.type + '. Data : ' + ObjectTyString(data);
    $('#logTextarea').val(trimTo1000(description + '\n' + $('#logTextarea').val()))
}